package com.xbongbong.paas.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.pojo.workflow.WorkflowSubDataPoJo;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.pro.enums.workflow.WorkflowValueTypeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.WorkflowOperationsPojo;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.pojo.nodes.WorkflowTitlePojo;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2021/06/23 16:34
 */
public class WorkflowUtil {


    /**
     * 根据文档（https://xbb.yuque.com/lfwuxq/vsf9sv/hcflv0#o4oem）的规则目标表单的子表单只能等于本表单同一子表单，目标表单的不同子表单可以等于本表单不同子表单
     * 动态获取子表单数据
     * @param workflowOperationsPojo 操作
     * @param startNodeId 触发节点id/开始节点id
     * @param formDataMap 节点的数据
     * @return
     */
    public static WorkflowSubDataPoJo getSubData(WorkflowOperationsPojo workflowOperationsPojo, Long startNodeId, Map<Long, PaasFormDataEntityExt> formDataMap) {
        WorkflowSubDataPoJo workflowSubDataPoJo = new WorkflowSubDataPoJo();
        JSONArray data = new JSONArray();
        Integer triggerNodeFlag = 0;
        PaasFormDataEntityExt triggerNodeData = formDataMap.get(startNodeId);
        Long nodeId = workflowOperationsPojo.getWorkflowNodeId();
        if (Objects.equals(WorkflowValueTypeEnum.FORMULA.getType(), workflowOperationsPojo.getValueType())) {
            String formula = workflowOperationsPojo.getFormulaInfo().getFormula();
            String[] formulaArray = RegexUtil.getFormulaAttr(formula);
            for (int i = 0; i < formulaArray.length; i++) {
                String formulaAttr = formulaArray[i];
                if (formulaAttr.contains(FieldTypeEnum.SUB_FORM.getEsalias())) {
                    String[] array = getAttrByFormula(formulaAttr);
                    triggerNodeFlag = Integer.valueOf(array[0]);
                    nodeId = Long.valueOf(array[1]);
                    if (Objects.equals(1, triggerNodeFlag)) {
                        // 获取触发节点的子表单的数据
                        data = triggerNodeData.getData().getJSONArray(array[3]);
                    } else {
                        // 获取获取多条节点的子表单的数据（此处是新建节点勾选的是基于多条记录逐条新增）
                        PaasFormDataEntity multiDataNodeData = formDataMap.get(nodeId);
                        data = multiDataNodeData.getData().getJSONArray(array[3]);
                    }
                    break;
                }
            }
        } else if (Objects.equals(WorkflowValueTypeEnum.DYNAMIC_VALUE.getType(), workflowOperationsPojo.getValueType())) {
            triggerNodeFlag = workflowOperationsPojo.getTriggerNodeFlag();
            List<String> list = ExplainUtil.getAttrByPoint(workflowOperationsPojo.getValueAttr());
            // 获取子表单的数据
            if (Objects.equals(1, triggerNodeFlag)) {
                // 获取触发节点的子表单的数据
                data = triggerNodeData.getData().getJSONArray(list.get(0));
            } else {
                // 获取获取多条节点的子表单的数据（此处是新建节点勾选的是基于多条记录逐条新增）
                PaasFormDataEntity multiDataNodeData = formDataMap.get(workflowOperationsPojo.getWorkflowNodeId());
                data = multiDataNodeData.getData().getJSONArray(list.get(0));
            }
        }
        // 子表单数据的节点，是触发节点还是获取多条节点
        workflowSubDataPoJo.setNodeId(nodeId);
        workflowSubDataPoJo.setSubData(data);
        return workflowSubDataPoJo;
    }


    public static String[] getAttrByFormula(String formulaAttr) {
        return formulaAttr.replaceAll("[\\{\\}]", "").split("\\.");
    }

    public static boolean validateFormula(String[] list, String formula) {
        return list.length > BasicConstant.THREE && (formula.contains("1.") || formula.contains("0."));
    }



    public static PaasFormDataEntityExt getFormData(WorkflowTransferPOJO workflowTransferPOJO) {
        Data workflowStartNodeData = workflowTransferPOJO.getData();
        return setData(workflowStartNodeData.getId(), workflowTransferPOJO.getCorpid(), workflowStartNodeData);
    }

    public static PaasFormDataEntityExt setData(Long dataId, String corpid, Data workflowData) {
        JSONObject data = workflowData.getData();
        return setData(dataId, corpid, data, workflowData.getFormId(), workflowData.getSaasMark(), workflowData.getBusinessType());
    }

    public static PaasFormDataEntityExt setData(Long dataId, String corpid, JSONObject data, Long formId, Integer saasMark, Integer businessType) {
        PaasFormDataEntityExt paasFormDataEntity = new PaasFormDataEntityExt();
        paasFormDataEntity.setId(dataId);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setCreatorId(data.getString(FieldTypeEnum.CREATORID.getAlias()));
        paasFormDataEntity.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
        paasFormDataEntity.setUpdateTime(data.getLong(FieldTypeEnum.UPDATETIME.getAlias()));
        paasFormDataEntity.setAddTime(data.getLong(FieldTypeEnum.ADDTIME.getAlias()));
        paasFormDataEntity.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));
        if (data.get(FieldTypeEnum.OWNERID.getAlias()) instanceof List) {
            List<String> list = JSON.parseArray(JSON.toJSONString(data.get(FieldTypeEnum.OWNERID.getAlias())), String.class);
            if (CollectionsUtil.isNotEmpty(list)) {
                // 审批后的负责人是个list，需要解析下
                paasFormDataEntity.setOwnerId(list.get(0));
            } else {
                paasFormDataEntity.setOwnerId(paasFormDataEntity.getCreatorId());
            }
        } else {
            paasFormDataEntity.setOwnerId(data.getString(FieldTypeEnum.OWNERID.getAlias()));
        }
        paasFormDataEntity.setData(data);
        paasFormDataEntity.setFormId(formId);
        paasFormDataEntity.setSaasMark(saasMark);
        paasFormDataEntity.setBusinessType(businessType);
        return paasFormDataEntity;
    }

    public static void getFormIdByTitle(List<WorkflowTitlePojo> titleList, Set<Long> workOrder, Set<Long> others, Set<Long> workflowNodeIdSet) {
        for (WorkflowTitlePojo pojo : titleList) {
            if (Objects.nonNull(pojo.getWorkflowNodeId()) && !Objects.equals(0L, pojo.getWorkflowNodeId())) {
                workflowNodeIdSet.add(pojo.getWorkflowNodeId());
            }
            //工单
            if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(),pojo.getBusinessType())) {
                workOrder.add(pojo.getFormId());
            } else {
                //其他表单
                others.add(pojo.getFormId());
            }
        }
    }

    /**
     * 如果不允许审批完成后允许编辑时，移掉审批通过的数据
     * @param allowEditAfterFinished
     * @param formDataList
     * @return void
     * @author 吴峰
     * @date 2020/10/10 16:14
     */
    public static void removeInApprovedEdit(boolean allowEditAfterFinished, List<PaasFormDataEntityExt> formDataList) {
        Iterator<PaasFormDataEntityExt> iterator = formDataList.iterator();
        while (iterator.hasNext()) {
            PaasFormDataEntityExt formData = iterator.next();
            boolean edit = isApprovedEdit(allowEditAfterFinished, formData);
            if (!edit) {
                // 清除掉不允许编辑的数据
                iterator.remove();
            }
        }

    }

    public static boolean isApprovedEdit(boolean editAfterFinished, PaasFormDataEntityExt formData) {
        if (editAfterFinished) {
            // 允许编辑
            return true;
        }
        // 单据审批通过的不允许编辑
        return !FlowStatusEnum.PASS.getType().equals(formData.getFlowStatus());
    }
}
